/**
 * Notifications Module
 * Handles all notification functionality including friend requests
 */
const notificationsModule = (function() {
    // DOM elements
    const notificationToggle = document.getElementById('notification-toggle');
    const notificationPanel = document.getElementById('notification-panel');
    const notificationOverlay = document.getElementById('notification-overlay');
    const notificationList = document.querySelector('.notification-list');
    const notificationBadge = document.querySelector('.notification-badge');
    
    // State
    let pendingRequests = [];
    let notificationCount = 0;
    
    /**
     * Initialize the notifications module
     */
    function init() {
        // Event listeners
        if (notificationToggle) {
            notificationToggle.addEventListener('click', toggleNotificationPanel);
        }
        
        if (notificationOverlay) {
            notificationOverlay.addEventListener('click', closeNotificationPanel);
        }
        
        document.querySelectorAll('.close-notification').forEach(btn => {
            btn.addEventListener('click', closeNotificationPanel);
        });
        
        // Add refresh button listener
        const refreshBtn = document.getElementById('refresh-notifications');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function() {
                console.log('Manually refreshing notifications');
                loadNotifications();
                // 添加旋转动画效果
                this.querySelector('i').classList.add('fa-spin');
                setTimeout(() => {
                    this.querySelector('i').classList.remove('fa-spin');
                }, 1000);
            });
        }
        
        document.querySelectorAll('.notification-tabs .tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.notification-tabs .tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                // Filter notifications based on tab
                const tabType = this.getAttribute('data-tab');
                filterNotifications(tabType);
            });
        });
        
        // Setup debug button if available (development only)
        const debugButton = document.getElementById('debug-load-notifications');
        if (debugButton) {
            // Only show in development environments
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                debugButton.style.display = 'inline-block';
                debugButton.addEventListener('click', function() {
                    console.log('Debug: Manually loading notifications');
                    loadNotifications();
                });
            }
        }
        
        // Load notifications when the page loads
        loadNotifications();
    }
    
    /**
     * Toggle notification panel visibility
     */
    function toggleNotificationPanel() {
        notificationPanel.classList.toggle('active');
        notificationOverlay.classList.toggle('active');
        
        // If panel is now visible, mark notifications as read
        if (notificationPanel.classList.contains('active')) {
            markAllAsRead();
        }
    }
    
    /**
     * Close notification panel
     */
    function closeNotificationPanel() {
        notificationPanel.classList.remove('active');
        notificationOverlay.classList.remove('active');
    }
    
    /**
     * Load all notifications including pending friend requests
     */
    function loadNotifications() {
        console.log('Loading notifications...');
        
        // 如果通知面板是可见的，显示加载状态
        if (notificationPanel && notificationPanel.classList.contains('active')) {
            if (notificationList) {
                // 添加加载指示器
                notificationList.innerHTML = '<div class="loading-notification"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
            }
        }
        
        // Fetch pending friend requests
        fetchPendingFriendRequests().then(requests => {
            console.log('Received', requests.length, 'pending friend requests');
            pendingRequests = requests;
            notificationCount = requests.length;
            
            // Update notification badge
            updateNotificationBadge();
            
            // Render notifications
            renderNotifications();
        }).catch(error => {
            console.error('Error loading notifications:', error);
            // 显示错误信息
            if (notificationList && notificationPanel && notificationPanel.classList.contains('active')) {
                notificationList.innerHTML = '<div class="error-notification">加载通知时出错，请点击刷新按钮重试</div>';
            }
        });
        
        // Here you could load other types of notifications as well
    }
    
    /**
     * Fetch pending friend requests from the server
     */
    function fetchPendingFriendRequests() {
        console.log('Fetching pending friend requests...');
        return fetch('/api/friendships/pending/current', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            return response.json();
        })
        .catch(error => {
            console.error('Error fetching friend requests:', error);
            // Return empty array on error to prevent breaking the chain
            return [];
        });
    }
    
    /**
     * Update the notification badge count
     */
    function updateNotificationBadge() {
        if (notificationBadge) {
            if (notificationCount > 0) {
                notificationBadge.textContent = notificationCount;
                notificationBadge.style.display = 'block';
            } else {
                notificationBadge.style.display = 'none';
            }
        }
    }
    
    /**
     * Render all notifications in the notification panel
     */
    function renderNotifications() {
        if (!notificationList) return;
        
        // Clear existing notifications
        notificationList.innerHTML = '';
        
        // If there are no notifications
        if (notificationCount === 0) {
            notificationList.innerHTML = '<div class="empty-notification">没有新通知</div>';
            return;
        }
        
        // Render friend requests
        pendingRequests.forEach(request => {
            const notification = createFriendRequestNotification(request);
            notificationList.appendChild(notification);
        });
    }
    
    /**
     * Create a friend request notification element
     */
    function createFriendRequestNotification(request) {
        const notification = document.createElement('div');
        notification.className = 'notification-item unread friend-request';
        notification.setAttribute('data-id', request.id);
        
        // Format timestamp
        const timestamp = new Date(request.createdAt);
        const timeAgo = getTimeAgo(timestamp);
        
        notification.innerHTML = `
            <div class="notification-avatar">
                <img src="${request.requester.avatarUrl || '/images/default-avatar.png'}" alt="User Avatar">
            </div>
            <div class="notification-content">
                <div class="notification-header">
                    <span class="notification-title">好友请求</span>
                    <span class="notification-time">${timeAgo}</span>
                </div>
                <p><strong>${request.requester.fullName || request.requester.username}</strong> 请求添加您为好友</p>
                ${request.requesterNote ? `<p class="request-note">"${request.requesterNote}"</p>` : ''}
                <div class="notification-actions">
                    <button class="btn btn-primary btn-sm accept-friend" data-id="${request.id}">接受</button>
                    <button class="btn btn-secondary btn-sm reject-friend" data-id="${request.id}">拒绝</button>
                </div>
            </div>
        `;
        
        // Add event listeners for accept/reject buttons
        notification.querySelector('.accept-friend').addEventListener('click', function(e) {
            e.stopPropagation();
            const friendshipId = this.getAttribute('data-id');
            acceptFriendRequest(friendshipId);
        });
        
        notification.querySelector('.reject-friend').addEventListener('click', function(e) {
            e.stopPropagation();
            const friendshipId = this.getAttribute('data-id');
            rejectFriendRequest(friendshipId);
        });
        
        return notification;
    }
    
    /**
     * Accept a friend request
     */
    function acceptFriendRequest(friendshipId) {
        fetch(`/api/friendships/${friendshipId}/accept`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Friend request accepted:', data);
            
            // Remove this request from pending list
            pendingRequests = pendingRequests.filter(req => req.id !== parseInt(friendshipId));
            notificationCount = pendingRequests.length;
            
            // Update UI
            updateNotificationBadge();
            renderNotifications();
            
            // Show success message
            showToast('好友请求已接受');
            
            // If we have a friends module, reload the friends list
            if (window.friendsModule && typeof window.friendsModule.loadFriends === 'function') {
                window.friendsModule.loadFriends();
            }
        })
        .catch(error => {
            console.error('Error accepting friend request:', error);
            showToast('处理好友请求时出错', 'error');
        });
    }
    
    /**
     * Reject a friend request
     */
    function rejectFriendRequest(friendshipId) {
        fetch(`/api/friendships/${friendshipId}/reject`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Friend request rejected:', data);
            
            // Remove this request from pending list
            pendingRequests = pendingRequests.filter(req => req.id !== parseInt(friendshipId));
            notificationCount = pendingRequests.length;
            
            // Update UI
            updateNotificationBadge();
            renderNotifications();
            
            // Show success message
            showToast('好友请求已拒绝');
        })
        .catch(error => {
            console.error('Error rejecting friend request:', error);
            showToast('处理好友请求时出错', 'error');
        });
    }
    
    /**
     * Filter notifications based on tab
     */
    function filterNotifications(tabType) {
        // For now we only handle all notifications
        renderNotifications();
    }
    
    /**
     * Mark all notifications as read
     */
    function markAllAsRead() {
        // This functionality can be implemented if needed
    }
    
    /**
     * Show a toast message
     */
    function showToast(message, type = 'success') {
        // Check if toast container exists
        let toastContainer = document.querySelector('.toast-container');
        
        if (!toastContainer) {
            // Create toast container if it doesn't exist
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container';
            document.body.appendChild(toastContainer);
        }
        
        // Create toast element
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.innerHTML = `<div class="toast-content">${message}</div>`;
        
        // Add to container
        toastContainer.appendChild(toast);
        
        // Show toast
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);
        
        // Remove toast after delay
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }
    
    /**
     * Get readable time ago string from date
     */
    function getTimeAgo(date) {
        const seconds = Math.floor((new Date() - date) / 1000);
        
        let interval = Math.floor(seconds / 31536000);
        if (interval >= 1) {
            return interval + "年前";
        }
        
        interval = Math.floor(seconds / 2592000);
        if (interval >= 1) {
            return interval + "月前";
        }
        
        interval = Math.floor(seconds / 86400);
        if (interval >= 1) {
            return interval + "天前";
        }
        
        interval = Math.floor(seconds / 3600);
        if (interval >= 1) {
            return interval + "小时前";
        }
        
        interval = Math.floor(seconds / 60);
        if (interval >= 1) {
            return interval + "分钟前";
        }
        
        return "刚刚";
    }
    
    // Public API
    return {
        init: init,
        loadNotifications: loadNotifications,
        toggleNotificationPanel: toggleNotificationPanel
    };
})();

// Initialize notifications when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    notificationsModule.init();
    
    // Check for new notifications every 30 seconds
    setInterval(function() {
        notificationsModule.loadNotifications();
    }, 30000); // 30000 ms = 30 seconds
});
